package unicamp.mc;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import container_classes.Credentials;
import container_classes.User;

public class LoginActivity extends Activity {
	
	private Button btOk,
				   btRegister;
	
	private Credentials userCred;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        btOk = (Button) findViewById(R.id.btOk);
        btOk.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) { 
				okClick(); 
			}
		});
        
        btRegister = (Button) findViewById(R.id.btCadastro);
        btRegister.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) { 
				regClick(); 
			}
		});
    }
    
    private void okClick(){
    	logIn();
    }
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	finish();
        	
        	Intent intent = new Intent();
        	intent.setClass(this, MainActivity.class);
        	startActivity(intent);
        }
        
        if(keyCode == KeyEvent.KEYCODE_HOME){}
        return super.onKeyDown(keyCode, event);
    }
    
	private void logIn(){   
    	EditText user,
    		     pwd;
    	
    	String username,
    		   password;
    	
    	
    	user = (EditText) findViewById(R.id.tbEmail);
    	pwd = (EditText) findViewById(R.id.tbSenha);
    	
    	username = getMail(user);
    	password = getPwd(pwd);
    	
    	int validLogin = validateCredentials(username, password);
    	
    	if (validLogin != 0) {
    		finish();
    		
    		Intent i = new Intent();
    		i.setClass(this, MainOnActivity.class);
    		startActivity(i);
    	}else{
    		showMsg("Login ou senha invalidos;");
    		user.setText("");
    		pwd.setText("");
    	}
    }

	private String getMail(EditText mail){
    	String ret;
    	
    	mail = (EditText) findViewById(R.id.tbEmail);
    	ret = mail.getText().toString();
    	
    	return ret;
    }
    
    private String getPwd(EditText pwd){
    	String ret;

    	ret = pwd.getText().toString();
    	
    	return ret;
    }
    
    private int validateCredentials(String username, String pwd){
    	userCred = new Credentials(username, pwd);
    	User user = new User();
    	return 1;//user.login(userCred);
    }

    private void showMsg(String msg) {
		AlertDialog alert = new AlertDialog.Builder(this).create();
				
		alert.setTitle("Ops!!");
		alert.setMessage(msg);
		alert.show();
	}
    
    private void regClick(){
    	Intent intent = new Intent();
    	intent.setClass(this, RegisterActivity.class);
    	startActivity(intent);
    }
}